/*
 * @Description: wcy
 * @Author: cy2020
 * @Date: 2022-02-25 09:05:33
 * @LastEditTime: 2022-02-25 19:44:54
 */
const iot = require('../../src/iot');
const { log, getAuthInfo } = require('../../src/utils');
const data = require('../data/pcrData.json');
const deviceClient = require("./devices");
const { v4: uuidv4 } = require('uuid');


const connectUrl = 'tcp://192.168.8.165:4321';

log.info('------------------------ 认证鉴权 ------------------------');
const deviceIot = iot.device(
    {
        connectUrl, // tcp服务器地址
        deviceName: deviceClient.deviceId, // 设备信息
        productKeys: deviceClient.deviceId, //
        deviceSecret: deviceClient.configuration.secureKey,
    },
    /**
     * 认证： 获取用户名和密码
     * 支持自定义认证规则
     * @param {} deviceName
     * @param {*} productKeys
     * @param {*} deviceSecret
     * @returns{ username,passward}
     */
    function (deviceName, productKeys, deviceSecret) {
        return getAuthInfo(deviceName, deviceSecret);
    }
);

log.info('------------------------ 测试传送实验数据 ------------------------');
//测试传送实验数据
setInterval(publish, 10000);
/**
 * 推送实验数据
 * topic格式为
 */

function publish() {
    let myData = {...data}
    myData.device_no =  deviceClient.deviceId;
    myData.create_time = new Date().getTime();
    myData.serial_no = deviceClient.deviceId.replace("-","") + myData.create_time;

    let eventsPcrDataMessage = {
        deviceId:  deviceClient.deviceId,
        messageId: uuidv4(),
        timestamp: new Date().getTime(),
        data: JSON.stringify(myData),
    };

    // 属性信息
    deviceIot.publish(
        `/device/CarryOnP1000Q/${deviceClient.deviceId}/events/pcrData`,
        eventsPcrDataMessage,
        function (error) {
            log.info(error);
        }
    );

    let propertiesMessage = {
        deviceId:  deviceClient.deviceId,
        messageId: uuidv4(),
        timestamp: new Date().getTime(),
        data: JSON.stringify({"value":20}),
    }    

    // 实验信息
    deviceIot.publish(
        `/device/CarryOnP1000Q/${deviceClient.deviceId}/properties/pcrName`,
        propertiesMessage,
        {
            qos: 0,
        },
        function (error) {
            log.info(error);
        }
    );    
}